package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.PublishBatchRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.CountDetailByBatchIdAndTypesBean;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.PublishBatch;
import com.ndp.fb.rdb.model.PublishBatchCSAName;
import com.ndp.fb.util.SQLUtil;

import java.util.Date;
import java.util.List;

/**
 * Created by Sisi on 15-2-27.
 */
@Service
public class PublishBatchRdbServiceImpl extends DaoTemplate implements PublishBatchRdbService {

    @Override
    public PublishBatch findById(Long id) {
        String sql = "SELECT * FROM publish_batch WHERE id = ?";
        return findOne(sql, new Object[]{id}, DefaultRowMapper.autoRowMapper(PublishBatch.class));
    }

    @Override
    public PublishBatch findById(Long id, String userId) {
        String sql = "SELECT * FROM publish_batch WHERE id = ? and user_id= ?";
        return findOne(sql, new Object[]{id, userId}, DefaultRowMapper.autoRowMapper(PublishBatch.class));
    }


    @Override
    public Pager<PublishBatch> findPagerByUserIdOrderByCreateTime(String userId, Integer firstResult, Integer sizeNo) {
        String sql = "select * from publish_batch where user_id = ? and publish_status<>-1 AND publish_status <> 4 ORDER BY create_time desc";
        return findPager(sql, new Object[]{userId}, firstResult, sizeNo, DefaultRowMapper.autoRowMapper(PublishBatch.class));
    }

    @Override
    public List<CountDetailByBatchIdAndTypesBean> countDetailByBatchIdAndTypes(Long batchId, String types) {
        String sql = "SELECT prr.type AS `type`, COUNT(1) AS `count` FROM publish_batch pb INNER JOIN publish_result pr ON pb.id = pr.batch_id" +
                " INNER JOIN publish_result_record prr ON prr.publish_result_id = pr.publish_result_id" +
                " WHERE pb.id = " + batchId + " AND prr.type in ("+ types  +") GROUP BY prr.type";
        List list = (List) getJdbcTemplate().query(sql, DefaultRowMapper.autoRowMapper(CountDetailByBatchIdAndTypesBean.class));
        if (list != null && list.size() > 0)
        {
            return list;
        } else
        {
            return null;
        }
    }


    @Override
    public List<PublishBatch> findByIdsAndUserId(Long[] ids, String userId) {
        String sql = "select * from publish_batch where user_id =";
        StringBuilder sqlE = new StringBuilder();
        sqlE.append(sql).append("'").append(userId).append("'")
                .append(" and id in (")
                .append(SQLUtil.appendPlaceholder(ids.length)).append(")")
                .append(" ORDER BY create_time desc");
        return getJdbcTemplate().query(sqlE.toString(), ids, DefaultRowMapper.autoRowMapper(PublishBatch.class));
    }


    @Override
    public PublishBatchCSAName findCSANameByBatchId(Long batchId) {
        String sql = "SELECT acg.name AS  campaign_name,as1.name AS adset_name, ag.name AS adgroup_name FROM " +
                "ad_campaign_group acg , ad_set as1 , ad_group ag WHERE  ag.publish_batch_id=? and acg.publish_batch_id=?" +
                " and as1.publish_batch_id=?";
        return  findOne(sql,new Object[]{batchId,batchId,batchId},DefaultRowMapper.autoRowMapper(PublishBatchCSAName.class));
    }

    @Override
    public Long save(PublishBatch o) {
        return saveResultId(o);
    }



    @Override
    public List<PublishBatch> searchPublishBatchByNameAndUserId(String batchName, String userId) {
        String sql = "SELECT * FROM publish_batch p where p.publish_batch_name = ? and p.user_id = ?";
        return getJdbcTemplate().query(sql, new Object[]{batchName, userId}, DefaultRowMapper.autoRowMapper(PublishBatch.class));
    }

    @Override
    public List<Long> findIdsByPublishStatus(int publishStatus) {
        String sql = "SELECT id FROM publish_batch p where p.publish_status = ? order by id";
        return getJdbcTemplate().queryForList(sql,new Object[]{publishStatus},Long.class);
    }

    @Override
    public Integer findResultCountByBatchIdAndTypes(Long batchId, Integer... type) {

        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT SUM(resultCount) resultCount FROM");
        sql.append(" (SELECT COUNT(*) resultCount FROM publish_result_record prr ");
        sql.append(" JOIN publish_result pr ON prr.publish_result_id = pr.publish_result_id");
        sql.append(" JOIN publish_batch pb ON pr.batch_id = pb.id");
        sql.append(" WHERE pb.id =").append(batchId);
        sql.append(" AND prr.type IN (");
        sql.append(SQLUtil.appendPlaceholder(type.length));
        sql.append(")");
        sql.append(" GROUP BY prr.publish_result_id ) temp");
        
        return getJdbcTemplate().queryForInt(sql.toString(), type);
    }

    @Override
    public List<PublishBatch> findByPublishStatus(int publishStatus) {
        String sql = "SELECT * FROM publish_batch  WHERE publish_status =?";
        return getJdbcTemplate().query(sql, new Object[]{publishStatus}, DefaultRowMapper.autoRowMapper(PublishBatch.class));
    }

    @Override
    public List<PublishBatch> findByGoingPublishStatus(int publishStatus1, int publishStatus2)
    {
        String sql = "SELECT * FROM publish_batch  WHERE publish_status =? OR  publish_status =?";
        return getJdbcTemplate().query(sql, new Object[]{publishStatus1, publishStatus2}, DefaultRowMapper.autoRowMapper(PublishBatch.class));
    }

    @Override
    public void updatePublishStatusById(Long batchId, int publishStatus) {
        String sql = "UPDATE publish_batch SET publish_status = ?  WHERE id = ? ";
        getJdbcTemplate().update(sql, new Object[]{publishStatus, batchId});
    }

    @Override
    public void updatePublishFail(Long batchId, String failType) {
        String sql = "UPDATE publish_batch SET publish_status = 3,fail_type=?  WHERE id = ? ";
        getJdbcTemplate().update(sql, new Object[]{failType, batchId});
    }

    @Override
    public void updateStatsAndRetryCntAndTimeById(Long batchId, int publishStatus)
    {
        String sql = "UPDATE publish_batch SET publish_status = ?, retry_cnt = retry_cnt+1, retry_time =?  WHERE id = ? ";
        getJdbcTemplate().update(sql, new Object[]{publishStatus, new Date(), batchId});
    }

    @Override
    public void updatePublishBathById(Long batchId, Integer publishStatus, Long userAudianceId, Integer accountCount, Integer campaignCount, Integer adsetCount, Integer adgroupCount, Integer creativeCount) {
        String sql = "UPDATE publish_batch SET publish_status = ?,user_audience_id = ?,all_account_count = ?,all_campaign_count = ?,all_adset_count = ?,all_adgroup_count = ?, all_adcreative_count = ? WHERE id = ? ";
        Object[] param  = new Object[]{publishStatus, userAudianceId, accountCount, campaignCount,
                adsetCount, adgroupCount, creativeCount, batchId};
        getJdbcTemplate().update(sql, param);
    }

    @Override
    public void deleteByBatchId(Long batchId) {
        String sql1 = "delete from publish_batch where id=?";
        String sql2 = "delete from publish_result where batch_id=?";
        getJdbcTemplate().update(sql1, new Object[]{batchId});
        getJdbcTemplate().update(sql2, new Object[]{batchId});
    }
}
